package com.example.administrator.stargo.api;

import com.example.administrator.stargo.utils.L;
import com.example.administrator.stargo.utils.T;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者： jl
 * 日期： 2017/11/22.
 */

public class HttpUtils {

    public static void doGet(final int action, Map<String, String> params, CacheMode cacheMode, final boolean showLoadingDialog, final HttpCallBack httpCallBack) {
        String url = getGetUrl(action, params);
        OkGo.get(url)
                .cacheKey(getUrl(action).toString())
                .tag(getUrl(action).toString())
                .cacheMode(cacheMode)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        L.e("url:" + request.getUrl());
                        L.e("method:" + request.getMethod());
                        if (showLoadingDialog)
                            httpCallBack.showLoadingDialog();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        L.e("result:" + s);
                        try {
                         /*   JSONObject jsonObject = new JSONObject(s);
                            int state = jsonObject.getInt("state");
                            String res = jsonObject.getString("res");
                            //失败
                            if (state != 200) {
                                httpCallBack.showErrorMessage(res);
                                return;
                            }
*/
                            //成功
                            httpCallBack.onSuccess(action, s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response != null) {
                            int httpCode = response.code();
                            switch (httpCode) {
                                case 400:
                                    L.e("请求的语法出错");
                                    T.show("请求的语法出错");
                                    break;
                                case 401:
                                    L.e("未授权");
                                    T.show("未授权");
                                    break;
                                case 403:
                                    L.e("请求被拒绝");
                                    T.show("请求被拒绝");
                                    break;
                                case 404:
                                    L.e("请求的接口不存在");
                                    T.show("请求的接口不存在");
                                    break;
                                case 408:
                                    L.e("请求超时");
                                    T.show("请求超时");
                                    break;
                                case 500:
                                    L.e("服务器错误");
                                    T.show("服务器错误");
                                    break;
                                case 503:
                                    L.e("服务器停机或正在维护");
                                    T.show("服务器停机或正在维护");
                                    break;
                            }
                            L.e(e.getMessage());
                        }
                    }

                });
    }

    public static void doPost(final int action, Map<String, String> params, CacheMode cacheMode, final boolean showLoadingDialog, final HttpCallBack httpCallBack) {
        String url = getUrl(action).toString();

        OkGo.post(url)
                .cacheKey(String.valueOf(action))
                .tag(String.valueOf(action))
                .cacheMode(cacheMode)
                .params(params, true)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);

                        if (showLoadingDialog)
                            httpCallBack.showLoadingDialog();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            //JSONObject jsonObject = new JSONObject(s);
                            // int state = jsonObject.getInt("state");
                            //String res = jsonObject.getString("list");
                          /*  //失败
                            if (state != 200) {
                                httpCallBack.showErrorMessage(res);
                                return;
                            }*/

                            //成功
                            httpCallBack.onSuccess(action, s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response == null)
                            return;
                        int httpCode = response.code();
                        switch (httpCode) {
                            case 400:
                                T.show("请求的语法出错");
                                break;
                            case 401:
                                T.show("未授权");
                                break;
                            case 403:
                                T.show("请求被拒绝");
                                break;
                            case 404:
                                T.show("请求的接口不存在");
                                break;
                            case 408:
                                T.show("请求超时");
                                break;
                            case 500:
                                T.show("服务器错误");
                                break;
                            case 503:
                                T.show("服务器停机或正在维护");
                                break;
                        }
                        L.e(e.getMessage());
                    }

                });
    }

    public static void uploadHeadOrBack(final int action, String filePath, final UploadCallBack uploadCallBack) {
        String url = getUrl(action).toString();
        ArrayList<File> files = new ArrayList<>();
        files.add(new File(filePath));
        OkGo.post(url)
                .cacheKey(String.valueOf(action))
                .isMultipart(true)
                .tag(String.valueOf(action))
                .addFileParams("file", files)
//                .params("file", new File(filePath))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        L.e("url:" + request.getUrl());
                        L.e("method:" + request.getMethod());
                        L.e("params:" + request.getParams().toString());
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        L.e("result:" + s);
                        try {
                           /* JSONObject jsonObject = new JSONObject(s);
                            int state = jsonObject.getInt("state");
                            String res = jsonObject.getString("res");
                            //失败
                            if (state != 200) {
                                uploadCallBack.showErrorMessage(res);
                                return;
                            }*/

                            //成功
                            uploadCallBack.onSuccess(action, s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                        super.upProgress(currentSize, totalSize, progress, networkSpeed);
                        uploadCallBack.onProgress(currentSize, totalSize, progress, networkSpeed);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response == null)
                            return;
                        int httpCode = response.code();
                        switch (httpCode) {
                            case 400:
                                T.show("请求的语法出错");
                                break;
                            case 401:
                                T.show("未授权");
                                break;
                            case 403:
                                T.show("请求被拒绝");
                                break;
                            case 404:
                                T.show("请求的接口不存在");
                                break;
                            case 408:
                                T.show("请求超时");
                                break;
                            case 500:
                                T.show("服务器错误");
                                break;
                            case 503:
                                T.show("服务器停机或正在维护");
                                break;
                        }
                        L.e(e.getMessage());
                    }

                });
    }

    public interface UploadCallBack {
        void onSuccess(int action, String res);

        void showErrorMessage(String s);

        void onProgress(long currentSize, long totalSize, float progress, long networkSpeed);
    }


    /**
     * 拼接get请求的url地址
     *
     * @param action
     * @param params
     * @return
     */
    public static String getGetUrl(int action, Map<String, String> params) {

        StringBuilder url = getUrl(action);

        if (params == null || params.isEmpty()) {
            return url.toString();
        }

        url.append("?");

        for (String key : params.keySet()) {
            url.append(key);
            url.append("=");
            url.append(params.get(key));
            url.append("&");
        }

        return url.toString();
    }

    public static StringBuilder getUrl(int Action) {
        StringBuilder url = new StringBuilder(UrlConstants.BASE_URL);
        String actionUrl = "";
        switch (Action) {
            case 0:
                break;
            case ACTION.REGIST://注册
                actionUrl = UrlConstants.REGIST;
                break;
            case ACTION.LOGIN://登陆
                actionUrl = UrlConstants.LOGIN;
                break;

            case ACTION.MATCHLIST://杯赛列表
                actionUrl = UrlConstants.MATCH;
                break;

            case ACTION.PERSONALDETAIL://杯赛详情
                actionUrl = UrlConstants.PERSONALDETAIL;
                break;

            case ACTION.CANSAIDUIWU://参赛队伍
                actionUrl = UrlConstants.CANSAIDUIWU;
                break;

            case ACTION.BONUSSETS://赛事奖金
                actionUrl = UrlConstants.BONUSSETS;
                break;

            case ACTION.MATCHROUND://对阵表轮次
                actionUrl = UrlConstants.MATCHROUND;
                break;

            case ACTION.ROUNDLIST://对阵列表
                actionUrl = UrlConstants.ROUNDLIST;
                break;

            case ACTION.CHAMPION://对阵表冠军
                actionUrl = UrlConstants.CHAMPION;
                break;

            case ACTION.PIPEILIST://匹配赛列表
                actionUrl = UrlConstants.PIPEILIST;
                break;
            case ACTION.MATCHBINUS://匹配赛奖励设置
                actionUrl = UrlConstants.MATCHBINUS;
                break;
            case ACTION.MATCHRANK://赛季排名
                actionUrl = UrlConstants.MATCHRANK;
                break;
            case ACTION.QUERYSTAR://赛季之星
                actionUrl = UrlConstants.QUERYSTAR;
                break;
            case ACTION.PERSONALINFOR://个人排名信息
                actionUrl = UrlConstants.PERSONALINFOR;
                break;
            case ACTION.MINEZHANJI://我的战绩
                actionUrl = UrlConstants.MINEZHANJI;
                break;
            case ACTION.MatchingEnroll://报名表
                actionUrl = UrlConstants.MatchingEnroll;
                break;
            case ACTION.SUBMITENROLL://判断是否已报名成功
                actionUrl = UrlConstants.SUBMITENROLL;
                break;
            case ACTION.NEWSMAINLIST://消息列表页面
                actionUrl = UrlConstants.NEWSMAINLIST;
                break;
            case ACTION.MYINFOEVALUATE://获取个人信息（匹配赛）
                actionUrl = UrlConstants.MYINFOEVALUATE;
                break;
            case ACTION.MATCHINGINFO://查询赛事信息
                actionUrl = UrlConstants.MATCHINGINFO;
                break;
            case ACTION.MATCHENROLL:
                actionUrl = UrlConstants.MATCHENROLL;
                break;
            case ACTION.SAVEACCOUNT:
                actionUrl = UrlConstants.SAVEACCOUNT;
                break;
            case ACTION.ACCOUNTBINDING:
                actionUrl = UrlConstants.ACCOUNTBINDING;
                break;
            case ACTION.BANGAREA:
                actionUrl = UrlConstants.BANGAREA;
                break;
            case ACTION.SAVEJUESE:
                actionUrl = UrlConstants.SAVEJUESE;
                break;
            case ACTION.SELECTJUESE:
                actionUrl = UrlConstants.SELECTJUESE;
                break;
            case ACTION.DELETEJUESE:
                actionUrl = UrlConstants.DELETEJUESE;
                break;
            case ACTION.CHANGEPASSCODE:
                actionUrl = UrlConstants.CHANGEPASSCODE;
                break;
            case ACTION.BESURECODE:
                actionUrl = UrlConstants.BESURECODE;
                break;
            case ACTION.CHANGEPASSNEW:
                actionUrl = UrlConstants.CHANGEPASSNEW;
                break;
            case ACTION.UPLOAD_HEADER:
                actionUrl = UrlConstants.UPLOAD_HEADER;
                break;
            case ACTION.PERSONALSYSTEMPIN:
                actionUrl = UrlConstants.PERSONALSYSTEMPIN;
                break;
            case ACTION.CHANGEPERSONAL:
                actionUrl = UrlConstants.CHANGEPERSONAL;
                break;
            case ACTION.LOGINSUBMIT:
                actionUrl = UrlConstants.LOGINSUBMIT;
                break;
            case ACTION.LOGINGCODE:
                actionUrl = UrlConstants.LOGINGCODE;
                break;
            case ACTION.LOGINCODELOGIN:
                actionUrl = UrlConstants.LOGINCODELOGIN;
                break;
            case ACTION.REGISTUSER:
                actionUrl = UrlConstants.REGISTUSER;
                break;
            case ACTION.PERSONALINFOMATION:
                actionUrl = UrlConstants.PERSONALINFOMATION;
                break;
            case ACTION.LOOKPERSONALRATE:
                actionUrl = UrlConstants.LOOKPERSONALRATE;
                break;
            case ACTION.PIPEIPERSONALDATA:
                actionUrl = UrlConstants.PIPEIPERSONALDATA;
                break;
            case ACTION.COMMENTDUIYOU:
                actionUrl = UrlConstants.COMMENTDUIYOU;
                break;
            case ACTION.QUERYDUIYOU:
                actionUrl = UrlConstants.QUERYDUIYOU;
                break;
            case ACTION.UPLOADCOMMENT:
                actionUrl = UrlConstants.UPLOADCOMMENT;
                break;
            case ACTION.USERBATTLEINFO:
                actionUrl = UrlConstants.USERBATTLEINFO;
                break;
            case ACTION.NOTICEFEFEREE:
                actionUrl = UrlConstants.NOTICEFEFEREE;
                break;
            case ACTION.GETBANGDINGJUESENUMBER:
                actionUrl = UrlConstants.GETBANGDINGJUESENUMBER;
                break;
            case ACTION.JOINMATCHLISTMINE:
                actionUrl = UrlConstants.JOINMATCHLISTMINE;
                break;
            case ACTION.GETLOCATIONDATA:
                actionUrl = UrlConstants.GETLOCATIONDATA;
                break;
            case ACTION.GETHOTMATCHLIST:
                actionUrl = UrlConstants.GETHOTMATCHLIST;
                break;
            case ACTION.GETMATCHINFOPIPEI:
                actionUrl = UrlConstants.GETMATCHINFOPIPEI;
                break;
            case ACTION.HOMEPAGEQIANDAO:
                actionUrl = UrlConstants.HOMEPAGEQIANDAO;
                break;
            case ACTION.GETHAVEQIANDAO:
                actionUrl = UrlConstants.GETHAVEQIANDAO;
                break;
            case ACTION.QUERYWINGIFTLIST:
                actionUrl = UrlConstants.QUERYWINGIFTLIST;
                break;
            case ACTION.DUIHUANLIBAO:
                actionUrl = UrlConstants.DUIHUANLIBAO;
                break;
            case ACTION.GETMINEMINGCI:
                actionUrl = UrlConstants.GETMINEMINGCI;
                break;
            case ACTION.BEISAIMATCHLISTNEW:
                actionUrl = UrlConstants.BEISAIMATCHLISTNEW;
                break;
        }
        url.append(actionUrl);
        return url;
    }

}
